package com.zkx.system.generator.service;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zkx.common.exception.APIException;
import com.zkx.system.generator.entity.*;
import com.zkx.system.generator.mapper.BookMapper;
import com.zkx.system.generator.mapper.RecordMapper;
import com.zkx.system.generator.mapper.RoleMapper;
import com.zkx.system.generator.mapper.UserMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zkx.common.result.ResultCode;
import com.zkx.common.utils.RedisUtil;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author ${author}
 * @since 2021-08-10
 */
@Service
public class RecordServiceImpl extends ServiceImpl<RecordMapper, Record> implements IRecordService {
    @Autowired
    RecordMapper recordMapper;
    @Autowired
    UserMapper userMapper;
    @Autowired
    BookMapper bookMapper;
    @Autowired
    RabbitTemplate rabbitTemplate;
    @Autowired
    RedisUtil redisUtil;
    //RedisUtil redisUtil = ApplicationContextProvider.getBean(RedisUtil.class);
    @Autowired
    UserServiceImpl userService;
    @Autowired
    RoleMapper roleMapper;
    @Autowired
    BookServiceImpl bookService;

    //借还书方法 ifBorrow 此行为是否为借书
    //@Transactional 事务注解
    @Transactional
    public synchronized String borrowOrReturnBook(Integer bookId,boolean ifBorrow,String token){
        //初始化user对象，userId属性
        Book book = bookMapper.selectById(bookId);
        //定义记录类型 保存指定用户，指定图书的最后一条记录
        Record record;
        UandRandA uandRandA = (UandRandA) redisUtil.get(token);
        Integer userId = uandRandA.getId();

        if(recordMapper.selectRecordUserIdAndBookId(userId, bookId).size()!=0){
            record = recordMapper.selectRecordUserIdAndBookId(userId,bookId).getFirst();
        }
        else{
            record = null;
        }

        //输入图书id不存在
        if(book==null){
            throw new APIException(ResultCode.BOOK_NOT_EXIST);
        }
        //此用户没有借过这本书
        else if(record==null){
            //如果此行为为 借书
            if(ifBorrow){
                //借还书业务方法 设置为异步方法执行
                rabbitTemplate.convertAndSend("hello",new W(null,userId,bookId,0));
                return "borrow success";
            }
            //如果此行为为还书
            else {
               throw new APIException(ResultCode.USER_NOT_BORROW_BOOK);
            }
        }
        //如果有借书记录 且最后一次借书没还 修改借书记录
        else if(record.getStatus().equals(0)){
            if(ifBorrow) {
                throw new APIException(ResultCode.USER_HAS_BORROW_BOOK);
            }
            else{
                rabbitTemplate.convertAndSend("hello",new W(record,userId,bookId,1));
                return "return success";
            }
        }
        //有借书记录，且最后一次借书已还 新增一条记录
        else{
            if(ifBorrow){
                rabbitTemplate.convertAndSend("hello",new W(record,userId,bookId,0));
                return "borrow success";
            }else {
                throw new APIException(ResultCode.USER_NOT_BORROW_BOOK);
            }
        }
    }

    //分页查看所有记录
    public IPage<RecordVO> selectAll(Integer pageNumber, Integer number,String token){
        if(pageNumber<=0||number<1){
            throw new APIException(ResultCode.PAGE_NUMBER_ILLEGAL);
        }
        else {
            // 1. 创建page
            IPage<Record> page = new Page<>(pageNumber, number);
            //2. 将page传到mapper
            return recordMapper.selectInfoPage(page);
        }
    }

    //分页查找指定图书的借还书记录
    public IPage<RecordVO> selectRecordByBookId(Integer bookId,Integer pageNumber, Integer number){
        if(pageNumber<=0||number<1){
            throw new APIException(ResultCode.PAGE_NUMBER_ILLEGAL);
        }
        else{
            if(bookService.ifIdExist(bookId)){
                IPage<Record> page = new Page<>(pageNumber,number);
                return recordMapper.selectBookInfoPage(page,bookId);
            }
            else{
                throw new APIException(ResultCode.BOOK_NOT_EXIST);
            }
        }
    }

    //分页查找指定用户的借还书记录
    public IPage<RecordVO> selectRecordByToken(String token,Integer pageNumber, Integer number){
        Integer userId;
        UandRandA uandRandA;
        uandRandA = (UandRandA)redisUtil.get(token);
        userId = uandRandA.getId();
        IPage<Record> page;
        if(pageNumber<=0||number<1){
            throw new APIException(ResultCode.PAGE_NUMBER_ILLEGAL);
        }
        else {
            page  = new Page<>(pageNumber, number);
            return recordMapper.selectUserInfoPage(page,userId);
        }
    }
}